<template>
  <div id="brand">
    <div style="margin: 5px; padding: 5px;">
      <el-button type="success" round @click="showAdd">+ 添加</el-button>
    </div>
    <!--    // 展示所有品牌名称-->
    <el-form-item label="品牌名称">
      <el-select
        v-model="brandId"
        placeholder="请输入品牌名称"
        size="large"
        style="width: 240px"
      >
        <el-option
          v-for="item in brandList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>

    <!--    // 展示商品分类-->
    <el-col :span="12">
      <el-form-item label="分类">
        <el-cascader
          :props="categoryProps"
          style="width: 100%"
          v-model="checkedCategoryIds"
        />
      </el-form-item>
    </el-col>
    <el-button type="primary" @click="fetchPage">搜索</el-button>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="分类名称" prop="categoryName" />
      <el-table-column label="品牌名称" prop="brandName" />
      <el-table-column label="品牌图标" prop="brandUrl">
        <template #default="scope">
          <el-image :src="scope.row.brandUrl" style="width: 80px" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button size="small" @click="showEdit(scope.row)">
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页页码-->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="page.pageNum"
        v-model:page-size="page.pageSize"
        :page-sizes="[2, 4, 6, 8]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="fetchPage"
        @current-change="fetchPage"
      />
    </div>

    <el-dialog v-model="dialogVisible" :title="action">
      <el-form-item label="品牌名称">
        <el-select
          v-model="brandId"
          placeholder="请输入品牌名称"
          size="large"
          style="width: 240px"
        >
          <el-option
            v-for="item in brandList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!--    // 展示商品分类-->
      <el-col :span="12">
        <el-form-item label="分类">
          <el-cascader
            :props="categoryProps"
            style="width: 100%"
            v-model="checkedCategoryIds"
          />
        </el-form-item>
      </el-col>
      <el-form-item align="right" #default="scope">
        <div v-if="categoryBrandId">
          <el-button type="primary" @click="updateCategoryBrand">
            提交
          </el-button>
        </div>
        <div v-else>
          <el-button type="primary" @click="addCategoryBrand">提交</el-button>
        </div>
        <el-button @click="dialogVisible == false">取消</el-button>
      </el-form-item>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import {
  FindCategoryByParentId,
  getAllBrand,
  findPage,
  doAddCategoryBrand,
  doUpdateCategoryBrand,
  deleteCategoryBrand,
} from '@/api/categoryBrand'
import { ElMessage, ElMessageBox } from 'element-plus'

const brandCategoryRequest = reactive({
  brandId: '',
  category1Id: '',
  category2Id: '',
  category3Id: '',
})
const page = reactive({
  pageNum: 1,
  pageSize: 4,
  total: 0,
})

const tableData = ref([])
const checkedCategoryIds = ref([])
const brandList = ref([])
const categoryBrandId = ref('')
// 懒加载商品分类
const props = {
  lazy: true,
  value: 'id',
  label: 'name',
  leaf: 'leaf',
  checkStrictly: true,
  async lazyLoad(node, resolve) {
    // 加载数据的方法
    if (typeof node.value == 'undefined') node.value = 0
    const { data } = await FindCategoryByParentId(node.value)
    data.forEach(function(item) {
      //hasChildren判断是否有子节点
      item.leaf = !item.hasChildren
    })
    resolve(data) // 返回数据
  },
}
const categoryProps = ref(props)
const brandId = ref('')
const dialogVisible = ref(false)
const action = ref('修改或添加')
// 获取商品列表
const getBrandList = async () => {
  const res = await getAllBrand()
  brandList.value = res.data
}

// 获取分页数据
const fetchPage = async () => {
  brandCategoryRequest.brandId = brandId.value
  // 处理三级分类的id
  if (checkedCategoryIds.value.length == 1) {
    brandCategoryRequest.category1Id = checkedCategoryIds.value[0]
  }

  if (checkedCategoryIds.value.length == 2) {
    brandCategoryRequest.category1Id = checkedCategoryIds.value[0]
    brandCategoryRequest.category2Id = checkedCategoryIds.value[1]
  }

  if (checkedCategoryIds.value.length == 3) {
    brandCategoryRequest.category1Id = checkedCategoryIds.value[0]
    brandCategoryRequest.category2Id = checkedCategoryIds.value[1]
    brandCategoryRequest.category3Id = checkedCategoryIds.value[2]
  }
  const res = await findPage(page.pageNum, page.pageSize, brandCategoryRequest)
  // 清空checkid
  // checkedCategoryIds.value = []
  brandCategoryRequest.brandId = ''
  brandCategoryRequest.category1Id = ''
  brandCategoryRequest.category2Id = ''
  brandCategoryRequest.category3Id = ''
  tableData.value = res.data.records
  page.total = res.data.total
}
const showAdd = () => {
  categoryBrandId.value = ''
  dialogVisible.value = true
  categoryBrandId.value = ''
  brandId.value = ''
  checkedCategoryIds.value = []
  brandCategoryRequest.brandId = ''
  brandCategoryRequest.category1Id = ''
  brandCategoryRequest.category2Id = ''
  brandCategoryRequest.category3Id = ''
  action.value = '添加'
}
const addCategoryBrand = async () => {
  brandCategoryRequest.brandId = brandId.value
  // 处理三级分类的id
  if (checkedCategoryIds.value.length == 1) {
    brandCategoryRequest.category1Id = checkedCategoryIds.value[0]
  }

  if (checkedCategoryIds.value.length == 2) {
    brandCategoryRequest.category1Id = checkedCategoryIds.value[0]
    brandCategoryRequest.category2Id = checkedCategoryIds.value[1]
  }

  if (checkedCategoryIds.value.length == 3) {
    brandCategoryRequest.category1Id = checkedCategoryIds.value[0]
    brandCategoryRequest.category2Id = checkedCategoryIds.value[1]
    brandCategoryRequest.category3Id = checkedCategoryIds.value[2]
  }
  const res = await doAddCategoryBrand(brandCategoryRequest)
  if (res.code === 200) {
    ElMessage.success('添加成功')
  }
  categoryBrandId.value = ''
  checkedCategoryIds.value = []
  brandCategoryRequest.brandId = ''
  brandCategoryRequest.category1Id = ''
  brandCategoryRequest.category2Id = ''
  brandCategoryRequest.category3Id = ''
  brandId.value = ''
  dialogVisible.value = false
  fetchPage()
}

// 显示编辑页面
const showEdit = row => {
  action.value = '修改'
  categoryBrandId.value = row.id
  dialogVisible.value = true
}
// 修改
const updateCategoryBrand = async () => {
  brandCategoryRequest.brandId = brandId.value
  // 处理三级分类的id
  if (checkedCategoryIds.value.length == 1) {
    brandCategoryRequest.category1Id = checkedCategoryIds.value[0]
  }

  if (checkedCategoryIds.value.length == 2) {
    brandCategoryRequest.category1Id = checkedCategoryIds.value[0]
    brandCategoryRequest.category2Id = checkedCategoryIds.value[1]
  }

  if (checkedCategoryIds.value.length == 3) {
    brandCategoryRequest.category1Id = checkedCategoryIds.value[0]
    brandCategoryRequest.category2Id = checkedCategoryIds.value[1]
    brandCategoryRequest.category3Id = checkedCategoryIds.value[2]
  }
  const res = await doUpdateCategoryBrand(
    categoryBrandId.value,
    brandCategoryRequest
  )
  if (res.code === 200) {
    ElMessage.success('添加成功')
  }
  categoryBrandId.value = ''
  checkedCategoryIds.value = []
  brandCategoryRequest.brandId = ''
  brandCategoryRequest.category1Id = ''
  brandCategoryRequest.category2Id = ''
  brandCategoryRequest.category3Id = ''
  brandId.value = ''
  fetchPage()
  dialogVisible.value = false
}

// 删除
const handleDelete = id => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const ref = await deleteCategoryBrand(id)
      if (ref.code === 200) {
        ElMessage.success('删除成功')
      } else ElMessage.error(ref.message)
      await fetchPage()
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

onMounted(() => {
  getBrandList()
  fetchPage()
})
</script>
<style scoped>
#brand .pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin: 20px 0; /* 可选：添加上下间距 */
}
</style>
